<template>
  <div class="upload-list-container">
    <el-upload
      ref="upload"
      list-type="picture-card"
      :auto-upload="false"
      multiple
      :limit='10'
      :on-exceed='exceedFn'
      :on-change='changeFn'
      action='#'
    >
      <i
        slot="default"
        class="el-icon-plus"
      ></i>
      <div
        slot="file"
        slot-scope="{file}"
      >
        <img
          class="el-upload-list__item-thumbnail"
          :src="file.url"
          alt=""
        >
        <span class="el-upload-list__item-actions">
          <span
            class="el-upload-list__item-preview"
            @click="handlePictureCardPreview(file)"
          >
            <i class="el-icon-zoom-in"></i>
          </span>
          <span
            v-if="!disabled"
            class="el-upload-list__item-delete"
            @click="handleRemove($event, file)"
          >
            <i class="el-icon-delete"></i>
          </span>
        </span>
      </div>
    </el-upload>
    <el-dialog
      :visible.sync="dialogVisible"
      :show-close='false'
    >
      <img
        width="100%"
        :src="dialogImageUrl"
        alt=""
      >
    </el-dialog>
  </div>
</template>

<script>
import { mapGetters } from 'vuex'
// 导入 cos 模块
const COS = require('cos-js-sdk-v5')

const cos = new COS({
  SecretId: 'AKIDQhw9c6RZWUJvNgrpZDlCZpztlVBjAacf',
  SecretKey: '5KVo4FJDzc6RhpoeNzSmgWI0eAX6XwFP'
})

export default {
  name: 'uploadImgList',
  data () {
    return {
      dataList: [],
      dialogImageUrl: '',
      dialogVisible: false,
      disabled: false,
      imageUrl: '' // 上传成功的图片地址
    }
  },
  computed: {
    ...mapGetters(['userInfo'])
  },
  methods: {
    // 删除已选图片 -> 点击事件
    handleRemove (e, file) {
      document
        .querySelector('.el-upload-list ')
        .removeChild(
          document.querySelector(`img[src="${file.url}"]`).parentNode.parentNode
        )
    },
    // 查看大图 -> 点击事件
    handlePictureCardPreview (file) {
      this.dialogImageUrl = file.url
      this.dialogVisible = true
    },
    // 文件超出个数限制 -> 回调函数
    exceedFn (files, fileList) {
      this.$message.error('最多只能上传10张图片！')
    },
    // 添加文件 -> 回调函数
    changeFn (files, fileList) {
      const arr = []
      fileList.forEach((item) => {
        arr.push(item.raw)
      })
      this.dataList = arr
    },
    // 手动上传文件列表
    submitUpload () {
      return new Promise((resolve, reject) => {
        if (!this.dataList.length) resolve('')
        this.dataList.forEach((file) => {
          const isLt2M = file.size / 1024 / 1024 < 2
          if (!isLt2M) {
            this.$message.error('上传图片大小不能超过 2MB!')
          }

          const name = Date.now() + this.userInfo.id + file.name
          cos.putObject(
            {
              Bucket: 'qjtwork-1314843671', // 存储桶的名称，必须
              Region: 'ap-guangzhou', // 存储桶所在地域，必须字段
              Key: name, // 文件名，必须
              StorageClass: 'STANDARD', // 上传模式, 标准模式
              Body: file // 上传文件对象
            },
            (err, data) => {
              if (err === null && data.statusCode === 200) {
                this.imageUrl += name ? `${name},` : ''
                document
                  .querySelector('.el-upload-list ')
                  .removeChild(
                    document.querySelector('.el-upload-list').lastChild
                  )
                if (!document.querySelector('.el-upload-list').lastChild) {
                  resolve(this.imageUrl)
                  this.$refs.upload.clearFiles()
                  this.dataList = []
                  this.imageUrl = ''
                }
              } else this.$message.error(err)
            }
          )
        })
      })
    }
  }
}
</script>
